const express = require('express');
const fs = require('fs');
const path = require('path');
const bodyParse = require('body-parser');
const { Console } = require('console');
const app = express();
const myResult = [];
app.use(bodyParse.urlencoded({ extended: true }));
app.use(bodyParse.json());

app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-methods', 'GET,POST');
    next();
})
app.post('/getQuestions', function (req, res, next) {
    let order = req.body.order;
    let questionData = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../data/question.json'), 'utf-8'));
    let questionResult = questionData[order];
    if (questionResult) {
        let { id, question, items } = questionResult;
        res.send({
            errorCode: 0,
            msg: 'OK',
            data: {
                id,
                question,
                items
            }
        })

    } else {
        res.send({
            errorCode: 1,
            nmsg: 'NO_DATA',
            data: myResult
        });
        myResult = [];
    }
});

app.post('/updateAnswer', (req, res, next) => {
    let { order, myAnswer } = req.body;
    let questionData = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../data/question.json'), 'utf-8'));
    let { id, question, items, answer } = questionData[order];
    myResult.push({
        qid: id,
        question,
        myAnswer: items[myAnswer],
        rightAnswer: items[answer],
        isRight: myAnswer == answer
    })

    res.send({
        errorCode: 0,
        msg: 'OK'
    })
})

app.listen(8000, 'localhost');